import Vue from 'vue'
import App from './App.vue'
import router from './router'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
import 'babel-polyfill'
import api from './api/index.js'
import dayjs from 'dayjs';
// 全局挂载 API 实例
Vue.prototype.$api = api

// 初始化全局状态（响应式处理）
const globalData = Vue.observable({
  userInfo: {
    nickname: ''
  }
})


Vue.filter('formatDate', (value) => {
    if (!value) return '';
    return dayjs(value).format('YYYY-MM-DD HH:mm:ss');
});
const sta = Vue.observable({
  adminInfo: {
    nickname: '',
  },
  isLogin: false,
  adminName: ''
})

Vue.prototype.$globalData = globalData
Vue.prototype.$sta = sta

// 安全初始化 Token
const initializeToken = () => {
  const token = localStorage.getItem('token')
  if (token) {
    // ✅ 验证 Token 有效性
    api.getUserInfo()
      .then(res => {
        if (res.status_code === 1) {
          api.service.defaults.headers.common['Authorization'] = `Bearer ${token}`
          updateUserInfo(res.data)
        } else {
          clearAuthData()
        }
      })
      .catch(() => {
        clearAuthData()
      })
  }
}

// 更新用户信息（响应式方法）
const updateUserInfo = (userData) => {
  Vue.set(globalData.userInfo, 'nickname', userData.nickname)
  Vue.set(globalData.userInfo, 'avatar', userData.avatar)
  Vue.set(globalData.userInfo, 'id', userData.id)
  // 根据需要扩展其他字段
}

// 清理认证数据（响应式方法）
export const clearAuthData = () => {
  localStorage.removeItem('token')
  delete api.service.defaults.headers.common['Authorization']
  Vue.set(sta, 'isLogin', false)
  Vue.set(globalData.userInfo, 'nickname', '')
}

Vue.config.productionTip = false

// 配置 ElementUI
Vue.use(ElementUI, { size: 'medium' })

// 路由守卫配置
router.beforeEach((to, from, next) => {
  document.title = to.meta.title || '二手交易平台'

  // ✅ 需要认证的路径列表
  const authRequiredPaths = ['/me', '/message', '/release', '/order']
  
  // ✅ 统一认证检查
  if (authRequiredPaths.includes(to.path)) {
    const token = localStorage.getItem('token')
    
    if (!token) {
      return next('/login')
    }

    // ✅ 双重验证逻辑
    if (!globalData.userInfo.nickname) {
      api.getUserInfo()
        .then(res => {
          if (res.status_code === 1) {
            updateUserInfo(res.data)
            next()
          } else {
            clearAuthData()
            next('/login')
          }
        })
        .catch(() => {
          clearAuthData()
          next('/login')
        })
    } else {
      next()
    }
  } else {
    next()
  }
})

// 初始化 Vue 实例
new Vue({
  router,
  beforeCreate() {
    initializeToken() // 应用启动时安全初始化
  },
  render: h => h(App)
}).$mount('#app')